package cn.edu.zafu.bigdata.lb;

import java.io.*;
import java.util.Scanner;

/**
 * @Author: LiuBo
 */
public class FileReadWrite {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入您的学号：");
        String studentId = scanner.nextLine();
        System.out.println("请输入您想要保存的文本：");
        String content = scanner.nextLine();

        // 确保目录存在
        File directory = new File("files");
        if (!directory.exists()) {
            boolean isDirectoryCreated = directory.mkdir();
            if (!isDirectoryCreated) {
                System.err.println("无法创建目录 'files'");
                return; // 如果目录创建失败，则退出程序
            }
        }

        String fileName = "files/" + studentId + ".txt";
        writeToFile(fileName, content);
        System.out.println("文件内容如下：");
        readFromFile(fileName);

        scanner.close(); // 关闭scanner
    }

    private static void writeToFile(String fileName, String content) {
        try (FileWriter writer = new FileWriter(fileName)) {
            writer.write(content);
            System.out.println("文本已成功写入文件 " + fileName);
        } catch (IOException e) {
            System.err.println("写入文件时发生错误：" + e.getMessage());
        }
    }

    private static void readFromFile(String fileName) {
        try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            System.err.println("读取文件时发生错误：" + e.getMessage());
        }
    }
}